<template>
    <div class="commodity">
        <div class="page_img"></div>
        <div class="header">
            <van-nav-bar title="补样邀约" left-arrow @click-left="handleLeft" />
        </div>
        <searchHome v-model:value="queryParams.content" @onSubmit="onRefresh" @screenIsShow_on="screenIsShow_on" />
        <div class="commodity_classify">
            <div class="commodity_classify_items" @click="categoryIsShow = true">
                <span>{{ queryParams.categoryIdList.length ? '多品类' : '商品类目' }}</span>
                <img src="@/assets/commodity/icon_heisexiasanjiao.png" alt="">
            </div>
            <category :isShow="categoryIsShow" v-model:value="queryParams.categoryIdList" :multiple="true"
                @leftClick="categoryIsShow = false" @onSubmit="categorySubmit" />

            <div class="home-dates-box flex-align-center b-box" @click="showCalendar = true">
                <div class="flex-align-center">
                    <div class="home-index-data-date-first">
                        <div class="home-index-data-date-first-date">
                            {{ queryParams.outStartTime }}
                        </div>
                    </div>
                    <div class="line"></div>
                    <div class="home-index-data-date-second">
                        <div class="home-index-data-date-second-date">
                            {{ queryParams.outEndTime }}
                        </div>
                    </div>
                </div>

                <div class="r_img"></div>
            </div>
            <van-calendar v-model:show="showCalendar" switch-mode="year-month" allow-same-day type="range"
                @confirm="onConfirmCalendar" />

            <screenHome :isShow="screenIsShow" @onReset="screenReset" @onSubmit="screenSubmit"
                @close="screenIsShow = true">
                <searchScreen :type="screenType" v-model:discountPrice="queryParams.discountPrice"
                    v-model:recruiterType="queryParams.recruiterType"
                    v-model:recruiterDeptId="queryParams.recruiterDeptId"
                    v-model:recruiterDeptIdName="queryParams.recruiterDeptIdName"
                    v-model:recruiterUserId="queryParams.recruiterUserId"
                    v-model:outStartTime="queryParams.outStartTime" v-model:outEndTime="queryParams.outEndTime"
                    v-model:shelvesType="queryParams.shelvesType" ref="searchScreenRef" />
            </screenHome>
        </div>
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list v-model:loading="loading" :finished="finished" @load="onLoad">
                <template v-slot:finished>
                    <div class="nothing_div" v-if="list.length == 0 && !refreshing">
                        <van-image :src="nothingData"></van-image>
                        <div class="nothing_font">暂无数据</div>
                    </div>
                </template>
                <van-swipe-cell v-for="item in list" :key="item.id">
                    <commodityList :data="item" @click="routerGo(item)" />
                </van-swipe-cell>
            </van-list>
        </van-pull-refresh>

    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, onActivated } from 'vue'
import { useRouter } from 'vue-router';
import { getOutStockList } from '@/api/operation/index'
import { getEnvValue } from "@/utils/index";
// 类目
import category from '@/components/category/index.vue'
// 头部搜索框
import searchHome from '@/views/productHome/productLists/components/searchHome/indexNew.vue'
// 列表
import commodityList from './components/commodityList/index.vue'
// 搜索筛选
import screenHome from '@/views/productHome/productLists/components/screenHome/index.vue'
// 搜索筛选子项
import searchScreen from './components/searchScreen/index.vue'

const nothingData = new URL("@/assets/porduct/icon_zanwushuju.png", import.meta.url).href

const router = useRouter();
const searchScreenRef = ref()
// 类目开关
const categoryIsShow = ref(false)
// 筛选弹框
const screenIsShow = ref<boolean>(false)
const screenType = ref('all')

const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);
const list = ref<Array<any>>([]);
// 限制连续刷新数据重复问题
const refreFlag = ref(true)
// 计算当前日期的前六天
const calculateDateSevenDaysAgo = () => {
    const today = new Date()
    today.setDate(today.getDate() - 6)
    return today.toISOString().split('T')[0] // 格式化为 YYYY-MM-DD
}
// 当前日期
const currentDateBottom = () => {
    const today = new Date()
    today.setDate(today.getDate())
    return today.toISOString().split('T')[0] // 格式化为 YYYY-MM-DD
}

// 查询列表参数
const queryParams = ref<any>({
    content: '',
    categoryId: '',
    categoryName: '',
    recruiterType: '',
    recruiterUserId: '',
    recruiterDeptId: '',
    recruiterDeptIdName: '',
    discountPrice: '',
    outStartTime: calculateDateSevenDaysAgo(),
    outEndTime: currentDateBottom(),
    pageSize: 10,
    pageNum: 1,
    shelvesType: '',
    categoryIdList: []
})

const vantListScrollTop = ref<any>(0) // 滚动位置


// 在组件挂载完成后添加事件监听器
onMounted(() => {
    // 添加事件监听器
    window.addEventListener('resize', handleResize);
    functionScroll('init')
})
// 处理窗口大小变化的函数
const handleResize = () => {
};
// 在组件卸载前移除事件监听器
onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    functionScroll('delete')
});
/** 缓存页面进度条 */
const functionScroll = (type: string) => {
    const dom: any = document.querySelector('.van-pull-refresh')
    if (type === 'init') {
        dom?.addEventListener('scroll', (e: any) => {
            vantListScrollTop.value = e.target.scrollTop
        })
    } else if (type === 'delete') {
        dom?.removeEventListener('scroll', () => { });
    } else if (type === 'black') {
        dom.scrollTop = vantListScrollTop.value
    }
}
onActivated(() => {
    functionScroll('black')
})
// 获取列表数据
const getList = async () => {
    const { rows = [], total = 0 } = await getOutStockList(queryParams.value)
    refreFlag.value = true
    // 空数据 停止加载
    if (rows.length == 0) {
        list.value = [];
        finished.value = true;
        return;
    }
    // 有数据 赋值列表 加载状态结束
    rows.forEach((item: any) => {
        finished.value = false;
        if (item.productImage) {
            item.productImages = getEnvValue("VITE_APP_PIC_URL") + item.productImage.split(',')[0];
        } else {
            item.productImages = "";
        }
        list.value.push(item);
    });
    loading.value = false;
    refreshing.value = false;
    // 如果list长度大于等于总数据条数，数据全部加载完成
    if (list.value.length >= total) {
        finished.value = true; //结束加载
    }
}

// 筛选重置事件
const screenReset = () => {
    if (screenType.value == 'all') {
        queryParams.value = {
            content: '',
            categoryName: '',
            recruiterUserId: '',
            recruiterType: '',
            recruiterDeptId: '',
            recruiterDeptIdName: '',
            discountPrice: '',
            outStartTime: calculateDateSevenDaysAgo(),
            outEndTime: currentDateBottom(),
            pageSize: 10,
            pageNum: 1,
            shelvesType: '',
            categoryIdList: []
        }
    } else if (screenType.value == 'repertory') {
        queryParams.value.pageNum = 1
        queryParams.value.discountPrice = ''
    } else {
        queryParams.value.recruiterType = ''
        queryParams.value.recruiterDeptId = ''
        queryParams.value.recruiterDeptIdName = ''
        queryParams.value.recruiterUserId = ''
        searchScreenRef.value.recruiterList = []
    }
}
// 筛选完成事件
const screenSubmit = () => {
    screenIsShow.value = false
    onRefresh()
}
// 筛选完成事件
const screenIsShow_on = () => {
    screenIsShow.value = true;
    screenType.value = 'all'
}
// 跳转商品详情
const routerGo = (item: any) => {
    router.push({
        path: '/supplyInvitationDetail',
        query:{
            productId: item.productId,
            id: item.id
        }
    })
}

/** 加载更多 */
const onLoad = async () => {
    getList();
    queryParams.value.pageNum++;
};
/** 下拉 */
const onRefresh = () => {
    if (refreFlag.value) {
        refreFlag.value = false
        finished.value = false; // 清空列表数据
        refreshing.value = false;
        loading.value = true; // 加载状态
        queryParams.value.pageNum = 1; // 分页数赋值为1
        list.value = []; // 清空数组
        onLoad(); // 重新加载数据
    } else {
        finished.value = false;
        refreshing.value = false;
    }
};
// 商品类目选择完成
const categorySubmit = () => {
    categoryIsShow.value = false
    onRefresh()
}
/** 回退 */
const handleLeft = () => {
    router.push('/operation/operatepage')
}
//================================日历==============
const showCalendar = ref(false);
const formatDate = (date) => `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
const onConfirmCalendar = (values) => {
    const [start, end] = values;
    showCalendar.value = false;
    queryParams.value.outStartTime = formatDate(start)
    queryParams.value.outEndTime = formatDate(end)
    onRefresh()
};
</script>
<script lang="ts">
export default { name: 'supplyInvitation' }
</script>

<style lang="less" scoped>
@import url(./components/style/index.less);

:deep(.screenHome_bg) {
    height: calc(100vh - 144px);
}

:deep(.screenHome) {
    height: 70vh !important;
}
:deep(.commodity_classify) {
    margin-bottom: 0px !important;
    border-radius: 15px 15px 0px 0px;
    padding: 0 10px;
}

.commodity {
    height: 100vh;

    .header {
        filter: blur(0px);
        height: 90px;
        padding-top: 44px;
        box-sizing: border-box;
        width: 100%;
        position: relative;
        z-index: 6003;

        :deep(.van-icon-arrow-left) {
            color: #1a1b1c !important;
        }

        :deep(.van-nav-bar__title) {
            color: #1a1b1c !important;
            font-size: 18px !important;
            font-weight: 600 !important;

        }

        :deep(.van-nav-bar) {
            background: none !important;

            &::after {
                display: none !important;
            }
        }

        :deep(.van-nav-bar__content) {
            background-color: transparent !important;
        }
    }

    .page_img {
        background: url("@/assets/newui/productList/icon_shangpintu@2x.png");
        background-size: 100% 100%;
        position: absolute;
        width: 60px;
        height: 60px;
        top: 54px;
        right: 63px;

    }

    background: url(/src/assets/newui/productList/icon_shangpinbeijing@2x.png);
    background-size: 100%;
    background-repeat: no-repeat;
    position: relative;
}

.parmay_list {
    display: flex;
    align-items: center;
    height: 100%;

    .parmay {
        width: 70px;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        :deep(.van-image) {
            width: 46px;
            height: 46px;
            margin-bottom: 10px;
        }
    }
}

.van-pull-refresh {
    height: calc(100vh - 188px) !important;
    background: #f6f8fa;
}

.home-dates-box {
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    font-size: 12px;
    color: #0094FF;
    line-height: 12px;
    text-align: left;
    font-style: normal;
    width: 222px;
    height: 26px;
    background: #EEF0FF;
    border-radius: 5px;
    border: 1px solid #FFFFFF;
    filter: blur(0px);
    justify-content: space-between;
    padding-left: 10px;

    .line {
        width: 20px;
        height: 1px;
        background: #0094FF;
        margin-right: 5px;
    }

    .r_img {
        background: url("@/assets/newui/home/icon_rili@2x.png") no-repeat;
        background-size: 100% 100%;
        width: 24px;
        height: 24px;
    }
}
</style>